package ChannelTutorial.Demo02;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * Demo02 - ChannelFuture 异步操作详解 - 服务端
 * 
 * 简单的 Echo 服务端，用于客户端测试 ChannelFuture
 */
@Slf4j
public class Server {

    public static void main(String[] args) {
        log.info("=== ChannelFuture 异步操作演示 - 服务端 ===\n");
        
        new Thread(() -> {
            try {
                startEchoServer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 启动一个简单的 Echo 服务端用于测试
     */
    private static void startEchoServer() throws Exception {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                ByteBuf buf = (ByteBuf) msg;
                                log.info("[服务端] 收到: {}", buf.toString(StandardCharsets.UTF_8));
                                ctx.writeAndFlush(msg);
                            }
                        });
                    }
                });
            
            ChannelFuture bindFuture = b.bind(9000).sync();
            log.info("[服务端] 已启动，监听端口 9000\n");
            
            bindFuture.channel().closeFuture().sync();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}

